package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Description CategoryServiceImpl
 * @Author zhuzi
 * @Date 2023/09/23
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishMapper dishMapper;

    /**
     * 分类分页模糊查询
     *
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        Page page = (Page) categoryMapper.page(categoryPageQueryDTO.getName(), categoryPageQueryDTO.getType());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 创建分类
     *
     * @param categoryDTO
     */
    @Override
    public void createCategory(CategoryDTO categoryDTO) {
        // 校验数据合法性
        if (categoryDTO.getName() == null || categoryDTO.getSort() == null) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        Category category = categoryMapper.getCategoryByCategoryName(categoryDTO.getName());
        if (category != null) {
            throw new BaseException(MessageConstant.CATEGORY_EXISTS);
        }

        // 封装数据创建套餐
        category = Category.builder()
                .type(categoryDTO.getType())
                .name(categoryDTO.getName())
                .sort(categoryDTO.getSort())
                .status(StatusConstant.ENABLE)
                .build();
        categoryMapper.save(category);
    }

    /**
     * 启用或禁用分类
     *
     * @param status
     * @param id
     */
    @Override
    public void pickOrBan(Integer status, Long id) {
        // 校验数据合法性：分类是否存在、是否是启用状态启用或禁止状态禁止
        Category category = categoryMapper.getCategoryByCategoryId(id);
        log.info("Get category: {}", category);
        if (category == null || category.getId() == null || category.getStatus().equals(status)) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }

        // 禁售分类时需判断分类中处于起售状态的菜品个数是否为零
        if (Objects.equals(status, StatusConstant.DISABLE) && dishMapper.getCountOfEnableDishByCategoryId(id) > 0) {
            throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
        }

        // 禁售分类时需判断分类中处于起售状态的套餐个数是否为零
        if (Objects.equals(status, StatusConstant.DISABLE) && setmealMapper.getCountOfEnableSetmealByCategoryId(id) > 0) {
            throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
        }

        // 执行更改状态操作
        category.setStatus(status);
        categoryMapper.updateStatusByCategoryId(category);
    }

    /**
     * 根据类型查询分类
     *
     * @param type
     * @return
     */
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.getListByType(type);
    }

    /**
     * 根据分类id修改分类
     *
     * @param categoryDTO
     */
    @Override
    public void updateCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    /**
     * 根据id删除分类
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        // 起售中的分类不能删除
        Category category = categoryMapper.getCategoryByCategoryId(id);
        if (category.getStatus().equals(StatusConstant.ENABLE)) {
            throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);
        }
        // 判断当前分类是否关联套餐或者菜品
        if (category.getStatus().equals(StatusConstant.DISABLE)) {
            if (setmealMapper.getCountByCategoryId(id) > 0) {
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
            }
            if (dishMapper.getCountByCategoryId(id) > 0) {
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
            }
        }
        categoryMapper.delete(id);
    }

}
